package com.test.io.aio;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeServerHandler implements Runnable {
	
	private int port;
	CountDownLatch latch;
	AsynchronousServerSocketChannel asynchronousServerSocketChannel;
	
	public AsyncTimeServerHandler(int port){
		try {
			this.port=port;
			this.asynchronousServerSocketChannel=AsynchronousServerSocketChannel.open();
			this.asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
			System.out.println("time server is start in port:"+port);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	

	@Override
	public void run() {
		// TODO Auto-generated method stub

		try {
			this.latch=new CountDownLatch(1);
			System.out.println("ready to accept..");
			doAccept();
			this.latch.await();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
		
	}
	
	private void doAccept(){
		System.out.println("start to accept.. ");
		this.asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
	}

}
